<template>
  <Container
    title="相似图片管理"
    :open.sync="open"
    :zIndex="1002"
    :showSubmit="false"
    class="similarityDialog"
  >
    <div ref="scrollContainer" class="similarityContainer" style="height: 550px;overflow-y: auto">
      <div v-for="(group, groupIndex) in tableDataList" :key="groupIndex" class="mb-4">
        <div class="group-header">
          <span class="group-title">相似组 {{ groupIndex + 1 }} (共{{ group.relationList.length || 0 }}张图片)</span>
        </div>
        <el-row :gutter="24" style="margin: 0 !important;">
          <el-col
            :xs="12"
            :sm="8"
            :md="4"
            :lg="3"
            :xl="3"
            v-for="(item, index) in group.relationList || []"
            :key="item.id || index"
            style="padding-top: 9px;padding-bottom: 9px;"
          >
            <el-card :body-style="{ padding: '0px' }" shadow="hover" style="height: 220px;">
              <div slot="header" class="clearfix flex-row" @click.stop="clickItems(item)">
                <el-checkbox v-model="item.selected"></el-checkbox>
                <div class="flex-1" ></div>
                <div class="flex-row" style="margin:0" >
                  <el-button type="text" class="button" @click.stop="copyPath(item)" style="color:#4CAF50;margin-left: 10px">复制</el-button>
                  <el-button type="text" class="button" @click.stop="deleteImage(item.id)" style="color: red;margin-left: 10px">删除</el-button>
                </div>
              </div>

              <LazyLoadImage
                class="sim_image"
                fit="contain"
                :src="getPreviewPath(item.fileId, item)"
                :preview-src-list="srcList"
                :lazy="true"
              >
              </LazyLoadImage>

              <div class="title_content"  @click.stop="clickItems(item)" style="cursor: pointer;">
                <span :title="item.title">{{ item.title }}</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 加载中提示 -->
      <div v-if="loadingMore" class="loading-container">
        <el-spinner size="medium"></el-spinner>
        <span>加载中...</span>
      </div>

      <el-empty description="无数据" v-if="tableDataList.length <= 0"></el-empty>
    </div>

    <template #btn>
      <div class="flex-row flex-wrap fill-width">
        <div class="flex-row gap-5">
          <el-button type="success" plain size="mini" @click="init">刷新</el-button>
          <el-button type="primary" plain size="mini" @click="submit">重新查找相似图</el-button>
        </div>
        <div class="flex-1"></div>
        <pagination
          :total="total"
          :page-sizes="[100, 200, 300, 500]"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="getList"
          style="margin: 0!important; height: 100%; padding: 0!important; position: unset;"
        />
      </div>
    </template>

  </Container>
</template>

<script>
import Container from '@/views/imgManage/imgInfoManage/Container.vue'
import { deleteByIds, getSimilarImages, startFindSimilarImages } from '@/api/imgManage/image'
import LazyLoadImage from '@/components/LazyLoadImage/index.vue'
import { debounce } from '@/utils'

export default {
  name: 'SimilarityGraphManage',
  components: { LazyLoadImage, Container },
  props: {},
  data() {
    return {
      open: false,
      tableDataList: [],
      currentPage: 1,
      pageSize: 100,
      total: 0,
      loading: false,
      loadingMore: false,
      hasMore: true
    }
  },
  computed: {
    srcList() {
      return this.tableDataList.flatMap(group =>
        group.relationList?.map(item => this.getPreviewPath(item.fileId, item)) || []
      )
    },
    scrollContainer() {
      return this.$refs.scrollContainer
    }
  },
  watch: {
    open(newVal) {
      if (newVal) {
        this.init()
      }
    }
  },
  methods: {
    init() {
      this.currentPage = 1
      this.tableDataList = []
      this.loading = true
      this.open = true
      this.getList()
      this.setupScrollListener()
    },
    getList: debounce(async function(reset = false) {
      if (reset) {
        this.currentPage = 1
        this.tableDataList = []
      }
      // if (this.loading || !this.hasMore) return

      this.loading = true
      this.loadingMore = !reset

      this.tableDataList = []
      try {
        const res = await getSimilarImages({ pageNum: this.currentPage, pageSize: this.pageSize })
        const newData = res.rows || []
        this.total = res.total || 0

        // 合并数据
        if (reset) {
          this.tableDataList = newData
        } else {
          this.tableDataList = [...this.tableDataList, ...newData]
        }

        // 判断是否还有更多数据
        this.hasMore = this.currentPage * this.pageSize < this.total
      } catch (error) {
        console.error('获取相似图片列表失败', error)
        this.$modal.msgError('获取相似图片列表失败')
      } finally {
        this.loading = false
        this.loadingMore = false
      }
    },500),
    getPreviewPath(fileId, item) {
      if (item?.fileId?.startsWith("http")) {
        return item.fileId
      }
      return this.$config.urlFormat('/openApi/previewByBussId?bussid=' + fileId)
    },
    clickItems(item) {
      this.$set(item, 'selected', !item.selected)
    },
    async copyPath(item) {
      const imageSrc = item.fileId
      try {
        await navigator.clipboard.writeText(imageSrc);
        this.$message.success('复制成功')
      } catch (error) {
        console.error('复制失败:', error);
        this.$message.error('复制失败')
      }
    },
    deleteImage(ids) {
      if (!ids) {
        const selectedIds = []
        this.tableDataList.forEach(group => {
          group.relationList?.forEach(item => {
            if (item.selected) selectedIds.push(item.id)
          })
        })
        ids = selectedIds.join(",")
      }

      if (!ids) {
        return this.$modal.msgWarning("请选择数据！");
      }

      this.$confirm(`确定要删除这${ids.split(',').length}条吗？`, '提示', { type: 'warning' }).then(
        () => {
          this.$modal.loading("正在删除，请稍候...");
          deleteByIds(ids).then(res => {
            if (res.code == 200) {
              this.getList(true) // 刷新列表
              this.$modal.msgSuccess("删除成功！");
            } else {
              this.$modal.msgError("删除失败！");
            }
            this.$modal.closeLoading()
          }).catch(e => {
            this.$modal.closeLoading()
          })
        }
      )
    },
    async submit() {
      this.$modal.loading("正在查找相似，请稍候...");
      try {
        await startFindSimilarImages()
        await this.getList(true) // 查找完成后刷新列表
        this.$modal.msgSuccess("查找成功！")
      } catch (error) {
        console.error('查找相似图片失败', error)
        this.$modal.msgError('查找相似图片失败')
      } finally {
        this.$modal.closeLoading()
      }
    },
    setupScrollListener() {
      if (!this.scrollContainer) return

      this.scrollContainer.addEventListener('scroll', this.handleScroll)
    },
    handleScroll() {
      if (this.loading || !this.hasMore) return

      const { scrollTop, scrollHeight, clientHeight } = this.scrollContainer
      // 当滚动到距离底部100px以内时加载下一页
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        this.currentPage++
        this.getList()
      }
    },
    // 销毁时移除滚动监听
    beforeDestroy() {
      if (this.scrollContainer) {
        this.scrollContainer.removeEventListener('scroll', this.handleScroll)
      }
    }
  },
  mounted() {
  }
}
</script>

<style lang="scss">
.similarityDialog {
  .el-dialog {
    height: 75% !important;
  }

  .el-dialog__body {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.similarityContainer {
  flex: 1;
  overflow-y: auto;

  .sim_image {
    width: 100%;
    display: block;
    height: 120px;
    object-fit: contain;
    padding-top: 5px;
  }

  .el-card {
    display: flex;
    flex-direction: column;

    .el-card__body {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;

      .el-image {
        height: 100%;
      }

      .title_content {
        padding: 10px 5px;
        text-align: center;
      }
    }
  }

  .group-header {
    padding: 10px 0;

    .group-title {
      font-weight: bold;
      color: #303133;
    }
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    color: #606266;
  }
}
</style>
